'use strict';
const path = require('path');
const fs = require('fs');
/**
 * 实体基类
 */
class BaseWork {
    constructor(parent) {
        this.isDebug = this._loadIsDebugSetting();
        this.entityName = 'BaseWork';
        this.parent = parent;
        this.redisPrototype = [];
        this.records = {};
    }
    async init() {
        await this.getRecords();
    }
    _loadIsDebugSetting() {
        try {
            const baseConfigPath = path.resolve(process.cwd(), 'config/baseConfig.json');
            if (fs.existsSync(baseConfigPath)) {
                const configContent = fs.readFileSync(baseConfigPath, 'utf8');
                const config = JSON.parse(configContent);
                return config.isDebug === true;
            }
        } catch (error) {
            console.error('[Logger] 加载baseConfig.json失败，默认为开发环境:', error);
        }

        // 默认为true，保留原有行为
        return process.env.NODE_ENV !== 'production';
    }
    //保证每个记录不超过20的长度
    async addRecords(key, num) {
        // 如果num为空，则默认设置为20
        if (num === undefined || num === null) {
            num = 20;
        }

        // 如果this[key]是数组，则确保其长度不超过num
        if (Array.isArray(this[key])) {
            this[key] = this[key].slice(0, num);
        }
        // 如果this[key]是对象，则确保其键值对数量不超过num
        else if (typeof this[key] === 'object' && this[key] !== null) {
            const keys = Object.keys(this[key]);
            if (keys.length > num) {
                const reducedObj = {};
                for (let i = 0; i < num; i++) {
                    reducedObj[keys[i]] = this[key][keys[i]];
                }
                this[key] = reducedObj;
            }
        }
        this.setRecords();
    }
    async getRecords() {
        this.records = await Redis.get(`${this.parent.entityName}:${this.parent.pid}_${this.entityName}`);
        if (this.records) {
            for (let i = 0; i < this.redisPrototype.length; i++) {
                this[this.redisPrototype[i]] = this.records[this.redisPrototype[i]];
            }
        }
    }
    async setRecords() {
        for (let i = 0; i < this.redisPrototype.length; i++) {
            this.records[this.redisPrototype[i]] = this[this.redisPrototype[i]];
        }
        Redis.set(`${this.parent.entityName}:${this.parent.pid}_${this.entityName}`, JSON.stringify(this.records));
    }
}

module.exports = BaseWork;